import { pageRange, updateStateRange } from '@/services/api/api-assess-week-collect-article-range';
import {
  exportRank,
  rank,
  rankAnalysis,
  rankInit
} from '@/services/api/api-assess-week-collect-article-rank';
import { CloudDownloadOutlined } from '@ant-design/icons';
import { ActionType, ProCard, ProColumns, ProList, ProTable } from '@ant-design/pro-components';
import { Button, Card, Descriptions, message, Radio, Space, Tag } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddRange from './AddArticleRange';
import styles from './TableArticleRankStyle.less';
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';

interface TableArticleRankProps {}

const TableArticleRank: React.FC<TableArticleRankProps> = ({}) => {
  const access = useAccess();

  const rangeActionRef = useRef<ActionType>();
  const rankActionRef = useRef<ActionType>();

  const [searchParam, setSearchParamState] = useState<any>({
    datahubLevelId: '2000',
    rangeIds: [],
  });

  const [activeKey, setActiveKey] = useState<React.Key>('2000');

  const [rangeInitData, setRangeInitDataState] = useState<AssessWeekCollectArticleRankData.RankInit>();

  const [analysisData, setAnalysisDataState] =
    useState<AssessWeekCollectArticleRankData.RankAnalysis>();

  const [selectType, setSelectTypeState] = useState<string>('radio');

  const [selectRanges, setSelectRangesState] = useState<AssessWeekCollectArticleRangeData.RangePage[]>(
    [],
  );

  /**
   * 获取 初始化 数据
   * @param key
   */
  const loadRankInit = async () => {
    try {
      const response = await rankInit();
      if (response.code === 0) {
        const data = response.data;
        setRangeInitDataState(response.data);
        setSearchParamState({
          ...searchParam,
          rangeIds: [data.id],
        });
      }
    } catch (error) {}
  };

  /**
   * 获取 详情
   * @param key
   */
  const loadRankAnalysis = async (rangeIds: string[]) => {
    try {
      const response = await rankAnalysis({
        rangeIds: rangeIds,
      });
      if (response.code === 0) {
        const data = response.data;
        setAnalysisDataState(response.data);
      }
    } catch (error) {}
  };

  useEffect(() => {
    loadRankInit();
  }, []);

  const columns: ProColumns<AssessWeekCollectArticleRankData.Rank>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          序号
        </span>
      ),
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      align: 'center',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          {activeKey === '2000' ? '单位' : '区域'}
        </span>
      ),
      dataIndex: 'name',
      align: 'center',
      ellipsis: true,
      width: '23%',
      render: (dom, entity, index, action) => {
        return (
          <span
            style={{
              color: entity?.totalCount == undefined ? '#ff4d4f' : '',
            }}
          >
            {entity.name}
          </span>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          发稿总数
        </span>
      ),
      dataIndex: 'totalCount',
      align: 'center',
      sorter: true,
      width: '85px',
      render: (dom, entity, index, action) => {
        if (entity.totalCount == 0 || entity.totalCount == undefined) {
          return '';
        } else {
          return <>{entity.totalCount}</>;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          万
        </span>
      ),
      dataIndex: 'count10000',
      align: 'center',
      // sorter: true,
      width: '85px',
      sorter: true,
      render: (dom, entity, index, action) => {
        if (entity.count10000 == 0 || entity.count10000 == undefined) {
          return '';
        } else {
          return <Tag color={'blue'}>{entity.count10000}</Tag>;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          十万
        </span>
      ),
      dataIndex: 'count100000',
      align: 'center',
      // sorter: true,
      width: '85px',
      sorter: true,
      render: (dom, entity, index, action) => {
        if (entity.count100000 == 0 || entity.count100000 == undefined) {
          return '';
        } else {
          return <Tag color={'cyan'}>{entity.count100000}</Tag>;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          百万
        </span>
      ),
      dataIndex: 'count1000000',
      align: 'center',
      // sorter: true,
      width: '85px',
      sorter: true,
      render: (dom, entity, index, action) => {
        if (entity.count1000000 == 0 || entity.count1000000 == undefined) {
          return '';
        } else {
          return <Tag color={'green'}>{entity.count1000000}</Tag>;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          千万
        </span>
      ),
      dataIndex: 'count10000000',
      align: 'center',
      // sorter: true,
      width: '85px',
      sorter: true,
      render: (dom, entity, index, action) => {
        if (entity.count10000000 == 0 || entity.count10000000 == undefined) {
          return '';
        } else {
          return <Tag color={'gold'}>{entity.count10000000}</Tag>;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          亿
        </span>
      ),
      dataIndex: 'count100000000',
      align: 'center',
      // sorter: true,
      width: '85px',
      sorter: true,
      render: (dom, entity, index, action) => {
        if (entity.count100000000 == 0 || entity.count100000000 == undefined) {
          return '';
        } else {
          return <Tag color={'red'}>{entity.count100000000}</Tag>;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          更新日期
        </span>
      ),
      dataIndex: 'editTime',
      align: 'center',
      width: '120px',
      hideInTable: selectType == 'checkbox',
    },
  ];

  return (
    <ProCard split="vertical" loading={rangeInitData == undefined}>
      <ProCard colSpan="384px" ghost>
        <ProList<AssessWeekCollectArticleRangeData.RangePage>
          headerTitle={
            <Radio.Group
              defaultValue={'radio'}
              optionType="button"
              buttonStyle="solid"
              size="middle"
              onChange={(e) => {
                if (e.target.value == 'radio') {
                  setSelectRangesState([selectRanges[selectRanges.length - 1]]);
                  setSearchParamState({
                    ...searchParam,
                    rangeIds: [searchParam.rangeIds[searchParam.rangeIds.length - 1]],
                  });
                  loadRankAnalysis([searchParam.rangeIds[searchParam.rangeIds.length - 1]]);
                }
                rankActionRef.current?.reloadAndRest();

                setSelectTypeState(e.target.value);
              }}
            >
              <Radio.Button value="radio">单选</Radio.Button>
              <Radio.Button value="checkbox">多选</Radio.Button>
            </Radio.Group>
          }
          ghost
          toolBarRender={() => {
            return [
              <AddRange
                onRefurbish={function (): void {
                  loadRankInit();
                  rangeActionRef.current?.reloadAndRest();
                }}
              />,
            ];
          }}
          actionRef={rangeActionRef}
          request={async (params, sorter) => {
            const response = await pageRange({
              ...params,
            });

            setSelectRangesState(
              response.data?.data.filter((item) => item.id == rangeInitData?.id),
            );

            return {
              data: response.data?.data,
              success: true,
              total: response.data?.total,
            };
          }}
          rowKey="id"
          options={false}
          pagination={{
            showQuickJumper: true,
            showSizeChanger: false,
            defaultPageSize: 50,
          }}
          search={false}
          metas={{
            title: {
              dataIndex: 'startDate',
              title: '用户',
              render: (_, row) => {
                return (
                  <div
                    style={{
                      paddingLeft: 10,
                    }}
                  >
                    <Tag color={row.state == 1 ? 'green' : 'red'}>
                      {row.state == 1 ? '进行中' : '已结束'}
                    </Tag>
                    {row.startDate} - {row.endDate}
                  </div>
                );
              },
            },
            subTitle: {
              dataIndex: 'state',
              title: '用户',
              render: (_, row, index, action) => {
                return (
                  <a
                    onClick={async () => {
                      const response = await updateStateRange({
                        id: row.id,
                      });
                      if (response.code === 0) {
                        action?.reloadAndRest();
                      }
                    }}
                  >
                    {row.state == 1 ? '关闭' : '开启'}
                  </a>
                );
              },
            },
          }}
          rowClassName={(row: AssessWeekCollectArticleRangeData.RangePage) => {
            return searchParam?.rangeIds.includes(row.id) ? styles['split-row-select-active'] : '';
          }}
          onRow={(record) => {
            return {
              onClick: () => {
                if (record.id) {
                  if (selectType == 'radio') {
                    setSelectRangesState([record]);
                    setSearchParamState({
                      ...searchParam,
                      rangeIds: [record.id],
                    });
                    loadRankAnalysis([record.id]);
                  } else {
                    let list = selectRanges;
                    let rangeIds = searchParam.rangeIds;

                    if (rangeIds.length == 1) {
                      //数量=1

                      if (rangeIds.includes(record.id)) {
                        //点击的id 是 数组内的
                        //不执行
                      } else {
                        //点击的id 不是 数组内的
                        //执行 添加
                        rangeIds.push(record.id);
                        list.push(record);

                        setSelectRangesState(list);

                        setSearchParamState({
                          ...searchParam,
                          rangeIds: rangeIds,
                        });

                        loadRankAnalysis(rangeIds);
                      }
                    } else if (rangeIds.length > 1) {
                      if (rangeIds.includes(record.id)) {
                        rangeIds = rangeIds.filter((item: any) => item != record.id);

                        list = list.filter((item) => item.id != record.id);
                      } else {
                        rangeIds.push(record.id);
                        list.push(record);
                      }

                      setSelectRangesState(list);

                      setSearchParamState({
                        ...searchParam,
                        rangeIds: rangeIds,
                      });

                      loadRankAnalysis(rangeIds);
                    }
                  }

                  rankActionRef.current?.reloadAndRest();
                }
              },
            };
          }}
        />
      </ProCard>
      <ProCard
        ghost
        bodyStyle={{
          paddingLeft: 18,
        }}
      >
        <Card
          title={
            <>
              范围：
              <Space wrap>
                {selectRanges?.map((item) => (
                  <Tag>
                    {item.startDate} ~ {item.endDate}
                  </Tag>
                ))}
              </Space>
            </>
          }
          extra={
            <Button
              icon={<CloudDownloadOutlined />}
              type="primary"
              onClick={async () => {
                const response = await exportRank({ ...searchParam });
                if (response.code === 0) {
                  message.success('导出成功');
                }
              }}
            >
              导出本次范围数据
            </Button>
          }
          loading={analysisData == undefined}
        >
          <Descriptions size="small" column={3}>
            <Descriptions.Item label="发稿总量">{analysisData?.totalAll}</Descriptions.Item>
          </Descriptions>
          <Descriptions size="small" column={6}>
            <Descriptions.Item label="市属媒体">
              {analysisData?.totalCountLevel2000}
            </Descriptions.Item>
            <Descriptions.Item label="万">
              {`${analysisData?.recordCount10000Level2000} -
                  ${analysisData?.recordCount10000PercentageLevel2000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="十万">
              {`${analysisData?.recordCount100000Level2000} -
                  ${analysisData?.recordCount100000PercentageLevel2000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="百万">
              {`${analysisData?.recordCount1000000Level2000} -
                  ${analysisData?.recordCount1000000PercentageLevel2000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="千万">
              {`${analysisData?.recordCount10000000Level2000} -
                  ${analysisData?.recordCount10000000PercentageLevel2000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="亿">
              {`${analysisData?.recordCount100000000Level2000} -
                  ${analysisData?.recordCount100000000PercentageLevel2000}%`}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions size="small" column={6}>
            <Descriptions.Item label="区县媒体">
              {analysisData?.totalCountLevel3000}
            </Descriptions.Item>
            <Descriptions.Item label="万">
              {`${analysisData?.recordCount10000Level3000} -
                  ${analysisData?.recordCount10000PercentageLevel3000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="十万">
              {`${analysisData?.recordCount100000Level3000} -
                  ${analysisData?.recordCount100000PercentageLevel3000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="百万">
              {`${analysisData?.recordCount1000000Level3000} -
                  ${analysisData?.recordCount1000000PercentageLevel3000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="千万">
              {`${analysisData?.recordCount10000000Level3000} -
                  ${analysisData?.recordCount10000000PercentageLevel3000}%`}
            </Descriptions.Item>
            <Descriptions.Item label="亿">
              {`${analysisData?.recordCount100000000Level3000} -
                  ${analysisData?.recordCount100000000PercentageLevel3000}%`}
            </Descriptions.Item>
          </Descriptions>
        </Card>
        <ProTable<AssessWeekCollectArticleRankData.Rank>
          columns={columns}
          actionRef={rankActionRef}
          rowKey="id"
          request={async (params = {}, sorter) => {
            loadRankAnalysis(searchParam.rangeIds);

            const response = await rank({
              ...params,
              sorter,
              ...searchParam,
            });
            return {
              data: response.data,
              success: true,
              total: response.data?.length,
            };
          }}
          dateFormatter="id"
          defaultSize={'small'}
          pagination={false}
          search={false}
          options={{
            density: false,
            setting: false,
          }}
          ghost
          scroll={{
            x: '1100px',
          }}
          toolbar={{
            menu: {
              type: 'tab',
              activeKey: activeKey,
              items: [
                {
                  key: '2000',
                  label: <span>市属媒体</span>,
                },
                {
                  key: '3000',
                  label: <span>区县媒体</span>,
                },
              ],
              onChange: (key) => {
                setSearchParamState({
                  ...searchParam,
                  datahubLevelId: key,
                });
                setActiveKey(key as string);
                rankActionRef.current?.reloadAndRest();
              },
            },
          }}
        />
      </ProCard>
    </ProCard>
  );
};
export default TableArticleRank;
